﻿using Rsd.Dudu;
using Rsd.Dudu.Core;
using Rsd.Dudu.Helpers;
using Rsd.Faith.Core;
using Rsd.Faith.Models;
using Rsd.Faith.Report.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Rsd.Faith.Report.Services
{
    /// <summary>
    /// 分期账目处理
    /// </summary>
    public class ReportService : BaseService, IReportService
    {
        public override ServiceProxcy Proxcy =>  ServiceProxcy.Sington;

        /// <summary>
        /// 资金总账属期核算
        /// </summary>
        /// <param name="zongZhang"></param>
        /// <returns></returns>
        public ReportZiJinZongZhangModel ZiJinZongZhangHeSuan(ReportZiJinZongZhangModel zongZhang)
        { 
            var suoShuQi = zongZhang.SuoShuQi;
            var _suoShuQiP = suoShuQi.ConvertTo<int>() - 1;
            
            if (_suoShuQiP < 2000)
            {
                //核算 总账
                zongZhang.QiChuJinE_ZZ = 0;
                zongZhang.QiChuJinE_DT = 0;
            }
            else
            {
                var zongZhangP = MyType.GetObject<ReportZiJinZongZhangModel>(obj => obj.SuoShuQi == _suoShuQiP.ToString());

                //if (zongZhangP != null && zongZhangP.ZhuangTai != ZhuangMuZhuangTai.YHS)
                //{
                //    return new ErrorResult(-1, "上期(" + _suoShuQiP.ToString() + ")账目未扎帐核算，本期(" + suoShuQi + ")无法核算。", null);
                //}

                zongZhang.QiChuJinE_ZZ = zongZhangP.YuE_ZZ;
                zongZhang.QiChuJinE_DT = zongZhangP.YuE_DT;
            }

            zongZhang.YuE_ZZ = zongZhang.QiChuJinE_ZZ + zongZhang.JiaoCunJinE_ZZ - zongZhang.ShiYongJinE_ZZ;
            zongZhang.YuE_DT = zongZhang.QiChuJinE_DT + zongZhang.JiaoCunJinE_DT - zongZhang.ShiYongJinE_DT;
            zongZhang.ZhuangTai = (suoShuQi == DateTime.Now.Year.ToString()) ? ZhangMuZhuangTai.JZZ : ZhangMuZhuangTai.YHS;
            zongZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
             MyType.SaveObjects(zongZhang);
            return zongZhang;
        }

        /// <summary>
        /// 小区总账核算
        /// </summary>
        /// <param name="xiaoQuZongZhang"></param>
        /// <returns></returns>
        public int XiaoQuZongZhangHeSuan(BookXiaoQuZongZhangModel xiaoQuZongZhang)
        {
            var xiaoQuBianHao = xiaoQuZongZhang.XiaoQuBianHao;

            //缴存和使用分摊时直接核算
            //xiaoQuZongZhang.YuE_ZZ = xiaoQuZongZhang.JiaoCunJinE_ZZ - xiaoQuZongZhang.ShiYongJinE_ZZ;
            //xiaoQuZongZhang.YuE_DT = xiaoQuZongZhang.JiaoCunJinE_DT - xiaoQuZongZhang.ShiYongJinE_DT;
            //xiaoQuZongZhang.ZengZhiYuE = xiaoQuZongZhang.ZengZhiJinE - xiaoQuZongZhang.ZengZhiShiYong;
            //xiaoQuZongZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
            //MyType.SaveObjects(xiaoQuZongZhang);

            var _year = xiaoQuZongZhang.JianZhangRiQi.Year;

            var list = MyType.GetObjects<ReportXiaoQuZhangMuModel>(obj => obj.XiaoQuBianHao == xiaoQuBianHao);
            var list_all = new ReportXiaoQuZhangMuModel[DateTime.Now.Year - _year + 1];

            foreach (var r in list)
            {
                list_all[r.SuoShuQi.ConvertTo<int>() - _year] = r;
            }
            for (var i = 0; i < list_all.Length; i++)
            {
                var r = list_all[i];
                if (r == null)
                {
                    r = new ReportXiaoQuZhangMuModel() { SuoShuQi = (_year + i).ToString(), XiaoQuBianHao = xiaoQuBianHao, XiaoQuMingCheng = xiaoQuZongZhang.XiaoQuMingCheng, ZhangHuBianHao = xiaoQuZongZhang.ZhangHuBianHao };
                    r.SetState(Dudu.BizModel.ObjectStateType.New);
                    list_all[i] = r;
                }
                else
                {
                    r.SetState(Dudu.BizModel.ObjectStateType.Update);
                }
                if (i == 0)
                {
                    //第一期 核算
                    r.QiChuJinE_ZZ = 0;
                    r.QiChuJinE_DT = 0;
                }
                else
                {
                    var zongZhangP = list_all[i - 1];
                    r.QiChuJinE_ZZ = zongZhangP.YuE_ZZ;
                    r.QiChuJinE_DT = zongZhangP.YuE_DT;
                }

                xiaoQuZongZhang.JiaoCunJinE_ZZ += r.JiaoCunJinE_ZZ;
                xiaoQuZongZhang.JiaoCunJinE_DT += r.JiaoCunJinE_DT;
                xiaoQuZongZhang.ShiYongJinE_ZZ += r.ShiYongJinE_ZZ;
                xiaoQuZongZhang.ShiYongJinE_DT += r.ShiYongJinE_DT;

                r.YuE_ZZ = r.QiChuJinE_ZZ + r.JiaoCunJinE_ZZ - r.ShiYongJinE_ZZ + r.ShouYiJinE_ZZ;
                r.YuE_DT = r.QiChuJinE_DT + r.JiaoCunJinE_DT - r.ShiYongJinE_DT + r.ShouYiJinE_DT;

                r.ZhuangTai = (i == list_all.Length - 1) ? ZhangMuZhuangTai.JZZ : ZhangMuZhuangTai.YHS;
            }

            MyType.SaveObjects(list_all);

            return list_all.Length;
        }

        /// <summary>
        /// 小区楼栋账核算
        /// </summary>
        /// <param name="louDongZhang"></param>
        /// <returns></returns>
        public int LouDongZhangHeSuan(BookLouDongMingXiZhangModel louDongZhang)
        {
            var rs = 0;
            var xiaoQuBianHao = louDongZhang.XiaoQuBianHao;
            var list = MyType.GetObjects<ReportLouDongZhangMuModel>(obj => obj.ZhangHuBianHao == louDongZhang.ZhangHuBianHao);
            var _year = louDongZhang.JianZhangRiQi.Year;
            var list_all = new ReportLouDongZhangMuModel[DateTime.Now.Year - _year + 1];
            foreach (var r in list)
            {
                list_all[r.SuoShuQi.ConvertTo<int>() - _year] = r;
            }
            for (var i = 0; i < list_all.Length; i++)
            {
                //缴存和使用分摊时直接核算
                //louDongZhang.YuE_ZZ = louDongZhang.JiaoCunJinE_ZZ - louDongZhang.ShiYongJinE_ZZ;
                //louDongZhang.YuE_DT = louDongZhang.JiaoCunJinE_DT - louDongZhang.ShiYongJinE_DT;
                //louDongZhang.ZengZhiYuE = louDongZhang.ZengZhiJinE - louDongZhang.ZengZhiShiYong;
                //louDongZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
                //MyType.SaveObjects(louDongZhang);

                var mxZhang = list_all[i];
                if (mxZhang == null)
                {
                    mxZhang = new ReportLouDongZhangMuModel() { SuoShuQi = (_year + i).ToString(), XiaoQuBianHao = xiaoQuBianHao, LouDongHao = louDongZhang.LouDongHao, ZhangHuBianHao = louDongZhang.ZhangHuBianHao };
                    mxZhang.SetState(Dudu.BizModel.ObjectStateType.New);
                    list_all[i] = mxZhang;
                }
                else
                {
                    mxZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
                }

                if (i == 0)
                {
                    //第一期  核算
                    mxZhang.QiChuJinE_ZZ = 0;
                    mxZhang.QiChuJinE_DT = 0;
                }
                else
                {
                    var mxZhangP = list_all[i - 1];
                    mxZhang.QiChuJinE_ZZ = mxZhangP.YuE_ZZ;
                    mxZhang.QiChuJinE_DT = mxZhangP.YuE_DT;

                }

                mxZhang.YuE_ZZ = mxZhang.QiChuJinE_ZZ + mxZhang.JiaoCunJinE_ZZ - mxZhang.ShiYongJinE_ZZ + mxZhang.ShouYiJinE_ZZ;
                mxZhang.YuE_DT = mxZhang.QiChuJinE_DT + mxZhang.JiaoCunJinE_DT - mxZhang.ShiYongJinE_DT + mxZhang.ShouYiJinE_DT;
                mxZhang.ZhuangTai = (i == list_all.Length - 1) ? ZhangMuZhuangTai.JZZ : ZhangMuZhuangTai.YHS;
                MyType.SaveObjects(list_all.ToArray());

                rs += list_all.Length;
            }

            return rs;
        }

        /// <summary>
        /// 小区单元
        /// </summary>
        /// <param name="danYuanZhang"></param>
        /// <returns></returns>
        public int DanYuanZhangHeSuan(BookDanYuanMingXiZhangModel danYuanZhang)
        {
            var xiaoQuBianHao = danYuanZhang.XiaoQuBianHao;
            var list = MyType.GetObjects<ReportDanYuanZhangMuModel>(obj => obj.ZhangHuBianHao == danYuanZhang.ZhangHuBianHao);
            var _year = danYuanZhang.JianZhangRiQi.Year;
            var list_all = new ReportDanYuanZhangMuModel[DateTime.Now.Year - _year + 1];
            foreach (var r in list)
            {
                list_all[r.SuoShuQi.ConvertTo<int>() - _year] = r;
            }

            for (var i = 0; i < list_all.Length; i++)
            {
                //缴存和使用分摊时直接核算
                //danYuanZhang.YuE_ZZ = danYuanZhang.JiaoCunJinE_ZZ - danYuanZhang.ShiYongJinE_ZZ;
                //danYuanZhang.YuE_DT = danYuanZhang.JiaoCunJinE_DT - danYuanZhang.ShiYongJinE_DT;
                //danYuanZhang.ZengZhiYuE = danYuanZhang.ZengZhiJinE - danYuanZhang.ZengZhiShiYong;
                //danYuanZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
                //MyType.SaveObjects(danYuanZhang);

                var mxZhang = list_all[i];
                if (mxZhang == null)
                {
                    mxZhang = new ReportDanYuanZhangMuModel() { SuoShuQi = (_year + i).ToString(), XiaoQuBianHao = xiaoQuBianHao, LouDongHao = danYuanZhang.LouDongHao, DanYuanHao = danYuanZhang.DanYuanHao, ZhangHuBianHao = danYuanZhang.ZhangHuBianHao };
                    mxZhang.SetState(Dudu.BizModel.ObjectStateType.New);
                    list_all[i] = mxZhang;
                }
                else
                {
                    mxZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
                }

                if (i == 0)
                {
                    //第一期  核算
                    mxZhang.QiChuJinE_ZZ = 0;
                    mxZhang.QiChuJinE_DT = 0;
                }
                else
                {
                    var mxZhangP = list_all[i - 1];
                    mxZhang.QiChuJinE_ZZ = mxZhangP.YuE_ZZ;
                    mxZhang.QiChuJinE_DT = mxZhangP.YuE_DT;

                }

                mxZhang.YuE_ZZ = mxZhang.QiChuJinE_ZZ + mxZhang.JiaoCunJinE_ZZ - mxZhang.ShiYongJinE_ZZ + mxZhang.ShouYiJinE_ZZ;
                mxZhang.YuE_DT = mxZhang.QiChuJinE_DT + mxZhang.JiaoCunJinE_DT - mxZhang.ShiYongJinE_DT + mxZhang.ShouYiJinE_DT;
                mxZhang.ZhuangTai = (i == list_all.Length - 1) ? ZhangMuZhuangTai.JZZ : ZhangMuZhuangTai.YHS;
                 
            }

            MyType.SaveObjects(list_all.ToArray());
            return list_all.Length;
        }

        /// <summary>
        /// 按小区,属期 进行 分户期内账目核算：（缴存、使用、增值、余额）
        /// </summary> 
        /// <param name="fenHuZhang"></param>
        /// <returns></returns>
        public int FenHuHeSuan(BookFenHuZhangModel fenHuZhang)
        {
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            var count = 0;
            var _year = fenHuZhang.JianZhangRiQi.Year;
            var fenHuSuffix = new List<string>();
            for (var year = _year; year < DateTime.Now.Year; year++)
            {
                fenHuSuffix.Add(year.ToString());
            }
            var sqlList = new List<string>();
            foreach (var suoShuQi in fenHuSuffix)
            {
                //新建分户属期账目 report__fen_hu_zhang_mu 
                var sql_insert_report = string.Format("insert into report__fen_hu_zhang_mu{0} (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,fang_wu_bian_hao) SELECT id,'{0}' as 'suo_shu_qi', zhang_hu_bian_hao,xiao_qu_bian_hao,fang_wu_bian_hao from book__fen_hu_zhang where fang_wu_bian_hao like '{1}' and zhang_hu_bian_hao not in (select zhang_hu_bian_hao from report__fen_hu_zhang_mu{0} where fang_wu_bian_hao like '{1}') ;", suoShuQi, fenHuZhang.FangWuBianHao);

                //核算 分户帐(缴存) report__fen_hu_zhang_mu
                var sql_update_report = string.Format("update report__fen_hu_zhang_mu{0} as A,(select fang_wu_dai_ma, sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao  where suo_shu_qi = '{0}' and fang_wu_dai_ma ='{1}' and zhuang_tai = '{2}'  GROUP BY fang_wu_dai_ma ) B set A.jiao_cun_jin_e = B.jiao_cun_jin_e_zz where  A.fang_wu_bian_hao = B.fang_wu_dai_ma;", suoShuQi, fenHuZhang.FangWuBianHao, FaPiaoZhuangTai.RZ.ToString());

                //核算 分户帐(使用) report__fen_hu_zhang_mu
                var sql_update_fentan = string.Format("update report__fen_hu_zhang_mu{0} A,(select fang_wu_bian_hao,sum(fen_tan_jin_e) as 'shi_yong_jin_e' from biz__zi_jin_shi_yong_fen_tan_biao where  suo_shu_qi = '{0}' and fang_wu_bian_hao='{1}' and zhuang_tai = '{2}' GROUP BY fang_wu_bian_hao  ) B set A.shi_yong_jin_e = B.shi_yong_jin_e where A.fang_wu_bian_hao = B.fang_wu_bian_hao ;", suoShuQi, fenHuZhang.FangWuBianHao, FaPiaoZhuangTai.RZ.ToString());

                //核算 分户 本期增值 
                var sql_update_zengzhi = string.Format("update report__fen_hu_zhang_mu{0} A,(select fang_wu_bian_hao,sum(li_xi_he_ji) as 'zeng_zhi_jin_e' from bank__fenhu_shou_yi_biao{0} where  suo_shu_qi = '{0}' and xiao_qu_bian_hao='{1}' and zhuang_tai = '{2}' GROUP BY fang_wu_bian_hao  ) B set A.shou_yi_jin_e = B.zeng_zhi_jin_e where A.fang_wu_bian_hao = B.fang_wu_bian_hao ;", suoShuQi, fenHuZhang.FangWuBianHao, FaPiaoZhuangTai.RZ.ToString());

                sqlList.AddRange(new string[] { sql_insert_report, sql_update_report, sql_update_fentan, sql_update_zengzhi });

            }
            try
            {
                count = dbSession.DbService.ExecuteByTransaction(sqlList.ToArray());
            }
            catch (Exception ex)
            {
                ErrorCodesType.R10002.SubmitError(fenHuZhang.FangWuBianHao, ex.ToString());
            }
            return count;
        }

        /// <summary>
        ///  按小区进行 分户分期账目扎帐核算：上期余额 结转下期 期初金额
        /// </summary>
        /// <param name="fenHuZhang"></param>
        /// <returns></returns>
        public int FenHuZhaZhang(BookFenHuZhangModel fenHuZhang)
        {
            var _year = fenHuZhang.JianZhangRiQi.Year;
            var fenHuSuffix = new List<string>();
            for (var year = _year; year < DateTime.Now.Year; year++)
            {
                fenHuSuffix.Add(year.ToString());
            }
             
            var list = MyType.GetObjects<ReportFenHuZhangMuModel>(obj => obj.ZhangHuBianHao == fenHuZhang.ZhangHuBianHao, fenHuSuffix.ToArray());
            
            //分户所有属期
            var list_all = new ReportFenHuZhangMuModel[DateTime.Now.Year - _year + 1];

            foreach (var r in list)
            {
                list_all[r.SuoShuQi.ConvertTo<int>() - _year] = r;
            }

            for (var i = 0; i < list_all.Length; i++)
            {
                //缴存和使用分摊时直接核算
                //fenHuZhang.YuE = fenHuZhang.JiaoCunJinE - fenHuZhang.ShiYongJinE + fenHuZhang.ShouYiJinE;

                //fenHuZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
                //MyType.SaveObjects<BookFenHuZhangModel>(fenHuZhang);

                var fhZhang = list_all[i];
                if (fhZhang == null)
                {
                    fhZhang = new ReportFenHuZhangMuModel() { SuoShuQi = (_year + i).ToString(), XiaoQuBianHao = fenHuZhang.XiaoQuBianHao, FangWuBianHao = fenHuZhang.FangWuBianHao, ZhangHuBianHao = fenHuZhang.ZhangHuBianHao };
                    fhZhang.SetState(Dudu.BizModel.ObjectStateType.New);
                    list_all[i] = fhZhang;
                }
                else
                {
                    fhZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
                }

                if (i == 0)
                {
                    //第一期  核算
                    fhZhang.QiChuJinE = 0;
                }
                else
                {
                    var mxZhangP = list_all[i - 1];
                    fhZhang.QiChuJinE = mxZhangP.YuE; 
                }

                fhZhang.YuE = fhZhang.QiChuJinE + fhZhang.JiaoCunJinE - fhZhang.ShiYongJinE + fhZhang.ShouYiJinE;

                fhZhang.ZhuangTai = (i == list_all.Length - 1) ? ZhangMuZhuangTai.JZZ : ZhangMuZhuangTai.YHS;

                fhZhang.SetState(Dudu.BizModel.ObjectStateType.Update);
            }

            MyType.SaveObjects<ReportFenHuZhangMuModel>(list_all.ToArray());
            

            return list_all.Length;
        }

        /// <summary>
        /// 生成催缴单
        /// </summary>
        /// <param name="suoshuqi">当前所属期</param>
        /// <returns></returns>
        public int ShenChengCuiJiao(string suoshuqi)
        {
            var sql_del = "delete from report__zi_jin_cui_jiao_dan where suo_shu_qi ='"+ suoshuqi + "';";
           
            var sql_insert = @"INSERT into  report__zi_jin_cui_jiao_dan   (id,fang_wu_bian_hao,suo_shu_qi,cui_jiao_dan_jie_shou_ren,jie_shou_ren_dian_hua,fang_wu_di_zhi,dang_qian_zhang_hu_yu_e,cui_jiao_jin_e,cui_jiao_nei_rong,cui_jiao_fang_shi,cui_jiao_zhuang_tai ) 
SELECT A.id,A.fang_wu_bian_hao, A.suo_shu_qi,B.ye_zhu_xing_ming,'',B.bei_yong_di_zhi,A.yu_e + A.shou_yi_jin_e,B.shou_qi_jiao_cun_jin_e - (A.yu_e + A.shou_yi_jin_e),'补交维修资金','公告','催缴中' from book__fen_hu_zhang A ,info__fang_wu_xin_xi_biao B
where  A.fang_wu_bian_hao = B.bian_hao and A.yu_e + A.shou_yi_jin_e < B.shou_qi_jiao_cun_jin_e * 0.3";
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            return dbSession.DbService.ExecuteByTransaction(new string[] { sql_del,sql_insert });
        }

        /// <summary>
        /// 增值账目核算
        /// </summary>
        /// <returns></returns>
        public int ZengZhiHeSuan()
        {
            var sql_del = "DELETE from report__zeng_zhi_zhang_mu;";
            var sql_insert = @"INSERT into report__zeng_zhi_zhang_mu(id, suo_shu_qi, zhi_chu_jin_e, zhuang_tai)
SELECT uuid(), suo_shu_qi,sum(ifnull(shi_yong_jin_e, 0)) as 'zhi_chu_jin_e' ,'YHS' from bank__zeng_zhi_shi_yong GROUP BY suo_shu_qi;";

            var sql_update = @"update report__zeng_zhi_zhang_mu A LEFT JOIN
            (SELECT  suo_shu_qi, sum(ifnull(jin_e, 0)) as 'shou_ru_jin_e_zz' from bank__zeng_zhi_shou_yi GROUP BY suo_shu_qi) B
            on A.suo_shu_qi = B.suo_shu_qi set A.shou_ru_jin_e_zz = B.shou_ru_jin_e_zz ,A.yu_e = ifnull(B.shou_ru_jin_e_zz, 0) - A.zhi_chu_jin_e;";

            var sql_update_qichu = @"update report__zeng_zhi_zhang_mu A LEFT JOIN(SELECT(suo_shu_qi + 1) as 'suo_shu_qi', yu_e from report__zeng_zhi_zhang_mu ) B
        ON A.suo_shu_qi = B.suo_shu_qi set A.qi_chu_jin_e = B.yu_e;";

            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            return dbSession.DbService.ExecuteByTransaction(new string[] { sql_del , sql_insert , sql_update , sql_update_qichu });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override dynamic GetMonitorInfo()
        {
            throw new NotImplementedException();
        }
    }
}
